from django.shortcuts import render, redirect, HttpResponse
from django import forms

from io import BytesIO

from app01 import models
from app01.utils.bootstrap import BootStrapForm
from app01.utils.encrypt import md5
from app01.utils.code import check_code


class LoginForm(BootStrapForm):
    user_name = forms.CharField(
        label='用户名',
        widget=forms.TextInput,
        required=True,
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(render_value=True),
        required=True,
    )
    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput,
        required=True,
    )
    fields = [user_name, password, code]

    def clean_password(self):
        return md5(self.cleaned_data.get('password'))


def login(request):
    """登陆"""
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证码的校验
        user_inout_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', '')
        if code.upper() != user_inout_code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})

        # 数据库校验, 获取用户对象, 如果错误, 则为None
        admin_obj = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_obj:
            # 主动添加错误信息
            form.add_error('password', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})

        # 用户名,密码正确
        # 网站生成一个随机字符串, 写到用户浏览器的cookie中, session中
        request.session["info"] = {'id': admin_obj.id, 'name': admin_obj.user_name}
        # 登陆成功, 则设置7天免登陆
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/admin/list/')
    return render(request, 'login.html', {'form': form})


def logout(request):
    """注销"""
    request.session.clear()

    return redirect('/login/')


def image_code(request):
    """生成图像验证码"""
    # 调用PIL生成验证码图片
    img, code_str = check_code()

    # 写入到自己的session中, 以便后续获取验证码再进行校验
    request.session['image_code'] = code_str
    # 设置60s超时
    request.session.set_expiry(30)

    stream = BytesIO()
    img.save(stream, 'png')

    return HttpResponse(stream.getvalue())
